package com.scau.yangsuiyu.estore.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXTabPane;
import com.jfoenix.controls.JFXTextField;
import com.scau.yangsuiyu.estore.controller.myComponent.TopSpan;
import com.scau.yangsuiyu.estore.dababases.entity.Buyer;
import com.scau.yangsuiyu.estore.dababases.entity.Seller;
import com.scau.yangsuiyu.estore.dababases.entity.User;
import com.scau.yangsuiyu.estore.service.AppService;
import com.scau.yangsuiyu.estore.service.RegisterService;
import com.scau.yangsuiyu.estore.util.FormValidate;
import de.felixroske.jfxsupport.FXMLController;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * @author suiyu_yang
 * @description 注册页面Controller
 * @date 2019-05-23 18:31
 * @email suiyu_yang@163.com
 */
@FXMLController
public class RegisterController extends AnchorPane implements Initializable {
    private String registerRole = "buyer";
    @FXML
    private JFXTabPane registerTabPane;
    @FXML
    private Tab inputPhone;
    @FXML
    private Tab inputMoreMessage;
    @FXML
    private Tab registerSuccess;
    @FXML
    private JFXButton registerButton;
    @FXML
    private Button changeRoleButton;
    @FXML
    private JFXTextField phoneTF;
    @FXML
    private JFXTextField usernameTF;
    @FXML
    private JFXPasswordField passwordPF;
    @FXML
    private JFXPasswordField confirmPasswordPF;
    @FXML
    private Label phoneError;
    @FXML
    private Label phone;
    @FXML
    private Label passwordError;
    @FXML
    private Label confirmPasswordError;
    @FXML
    private Label usernameError;
    @FXML
    private Label roleLabel;
    @FXML
    private Label registerSuccessPhone;
    @FXML
    private Label registerSuccessName;

    @FXML
    private AnchorPane topSpanContainer;
    private User user;

    private FormValidate<TextField> validatePhone;
    private FormValidate<TextField> validateForm;
    private FormValidate<TextField> validatePsw;

    public RegisterController() {
        loadFXML();
    }

    private void loadFXML() {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/Register.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);
        try {
            fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void inputPhoneNext() {
        if (validatePhone.isValid()) { //前端格式验证
            switch (registerRole) {
                case "seller":
                    if (RegisterService.ifSellerPhoneExist(phoneTF.getText())) {
                        new Alert(Alert.AlertType.ERROR, "手机号已存在！").showAndWait();
                    } else {
                        phone.setText(phoneTF.getText());
                        nextPage();
                    }
                    break;
                case "buyer":
                    if (RegisterService.ifBuyerPhoneExist(phoneTF.getText())) {
                        new Alert(Alert.AlertType.ERROR, "手机号已存在！").showAndWait();
                    } else {
                        phone.setText(phoneTF.getText());
                        nextPage();
                    }
                    break;
                default:
                    break;
            }

        }
    }

    @FXML
    private void submit() {
        if (validateForm.isValid() && validatePsw.isValid()) {
            JSONObject resultJson = register();

            if (resultJson.getString("status").equals("success")) {  //注册成功

                if (registerRole.equals("seller")) {
                    user = resultJson.getObject("user", Seller.class);
                } else {
                    user = resultJson.getObject("user", Buyer.class);
                }

                registerSuccessName.setText(user.getUsername());
                registerSuccessPhone.setText(user.getPhone());
                nextPage();

            } else { //注册失败
                new Alert(Alert.AlertType.ERROR, resultJson.getString("result")).showAndWait();
            }

        }
    }

    @FXML
    private void changeRole() {
        if (registerRole.equals("buyer")) { //当前是买家注册
            registerRole = "seller";
            roleLabel.setText("卖家注册");
            changeRoleButton.setText("我是买家");
        } else { //当前是卖家注册
            registerRole = "buyer";
            roleLabel.setText("买家注册");
            changeRoleButton.setText("我是卖家");
        }
    }


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        topSpanContainer.getChildren().add(new TopSpan());

        validatePsw = new FormValidate<>();
        validatePhone = new FormValidate<>();
        validateForm = new FormValidate<>();

        TextField[] mobileNoTFs = {phoneTF};
        Label[] regularLabels = {phoneError};
        phoneError.setText("手机号错误！");
        validatePhone.installRegularValidation(mobileNoTFs, FormValidate.CHINAMOBILENO_REG, regularLabels);


        TextField[] requireTFs = {passwordPF, usernameTF};
        Label[] reqLabels = {passwordError, usernameError};
        passwordError.setText("密码栏不能为空");
        usernameError.setText("用户名不能为空");
        validateForm.installRequireValidation(requireTFs, reqLabels);

        confirmPasswordError.setText("两次密码输入不一致");
        validatePsw.installConfirmPswValidation(passwordPF, confirmPasswordPF, confirmPasswordError);

    }

    private void nextPage() {
        changeRoleButton.setVisible(false);
        SingleSelectionModel<Tab> selectionModel = registerTabPane.getSelectionModel();
        selectionModel.getSelectedItem().setDisable(true);
        selectionModel.selectNext();
        selectionModel.getSelectedItem().setDisable(false);
    }


    private JSONObject register() {
        String phone = phoneTF.getText();
        String username = usernameTF.getText();
        String password = passwordPF.getText();

        if (registerRole.equals("buyer")) {  //买家注册
            user = new Buyer();
            user.setPhone(phone);
            user.setUsername(username);
            user.setPsw(password);

            return new RegisterService(user).register();
        } else { //卖家注册
            user = new Seller();
            user.setPhone(phone);
            user.setUsername(username);
            user.setPsw(password);

            return new RegisterService(user).register();
        }
    }

    @FXML
    private void gotoLogin() {
        new AppService().gotoLogin();
    }
}
